package org.linlinjava.litemall.db.handler;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(Long[].class)
public class JsonLongArrayTypeHandler extends BaseTypeHandler<Long[]> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Long[] longs, JdbcType jdbcType) throws SQLException {
        try {
            String jsonString;
            if (longs == null) {
                jsonString = "null";
            } else {
                jsonString = objectMapper.writeValueAsString(longs);
            }
            preparedStatement.setString(i, jsonString);
        } catch (JsonProcessingException e) {
            throw new SQLException("Error converting array to JSON string", e);
        }
    }

    @Override
    public Long[] getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return parseArray(resultSet.getString(s));
    }

    @Override
    public Long[] getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return parseArray(resultSet.getString(i));
    }

    @Override
    public Long[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return parseArray(callableStatement.getString(i));
    }

    private Long[] parseArray(String jsonString) throws SQLException {
        if (StrUtil.isBlank(jsonString)) {
            return null;
        }

        try {
            return objectMapper.readValue(jsonString, Long[].class);
        } catch (JsonProcessingException e) {
            throw new SQLException("Error converting JSON string to array", e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
